import { getPersonaList } from '../../utils/persona'
const api = require('../../utils/api.js');

Page({
  data: {
    personaList: [],
    swiperCurrent: 0 // 当前选中项
  },
  
  onPrev() {
    const { swiperCurrent, personaList } = this.data;
    const newCurrent = swiperCurrent === 0 ? personaList.length - 1 : swiperCurrent - 1;
    this.setData({ swiperCurrent: newCurrent });
  },
  
  onNext() {
    const { swiperCurrent, personaList } = this.data;
    const newCurrent = swiperCurrent === personaList.length - 1 ? 0 : swiperCurrent + 1;
    this.setData({ swiperCurrent: newCurrent });
  },
  
  onLoad() {
    const list = getPersonaList();
    this.setData({
      personaList: list,
      swiperCurrent: 0 // 默认第一个
    });
  },

  onSwiperChange(e) {
    this.setData({ swiperCurrent: e.detail.current });
  },

  // 新增头像点击事件
  onAvatarTap(e) {
    const personaKey = e.currentTarget.dataset.key;
    const personaName = e.currentTarget.dataset.name;
    this.startConversation(personaKey, personaName);
  },

  onEmotionRecord() {
    wx.navigateTo({ url: '/pages/record/record' });
  },
  onHistoryTap() {
    wx.navigateTo({ url: '/pages/history/history' });
  },
  onPsychTest() {
    wx.navigateTo({ url: '/pages/test-list/test-list' });
  },
  
  onTalk() {
    const currentPersona = this.data.personaList[this.data.swiperCurrent];
    this.startConversation(currentPersona.key, currentPersona.name);
  },
  
  // 重构对话启动逻辑为共用方法
  startConversation(personaKey, personaName) {
    api.startConversation(personaKey).then(res => {
      if (res.status === 'success' || res.code === 200) {
        wx.navigateTo({
          url: `/pages/talk/talk?conversation_id=${res.conversation_id || res.data.conversation_id}` +
               `&persona=${personaKey}` +
               `&persona_name=${encodeURIComponent(personaName)}` +
               `&avatar_url=${encodeURIComponent(this.data.personaList.find(p => p.key === personaKey).avatar)}`
        });
      } else {
        wx.showToast({ title: '启动会话失败', icon: 'none' });
      }
    }).catch(() => {
      wx.showToast({ title: '网络错误', icon: 'none' });
    });
  }
});